package jane.mvc;

import jane.mvc.engine.AppDescriptor;
import jane.mvc.engine.Application;
import jane.mvc.engine.JaneMVCHandler;
import jane.mvc.engine.SanityChecker;
import jane.mvc.utils.MyLog;

import java.io.File;

import joptsimple.OptionParser;
import joptsimple.OptionSet;

import org.eclipse.jetty.server.Server;

public class Main
{

	/**
	 * @param args
	 */

	private static void createWorkDir()
	{

		File workDir = new File("work");

		if (!workDir.exists())
		{

			MyLog.warn("Work directory does not exist, creating it at the local directory...");

			File compiledtemplates = new File("work/compiledtemplates");
			File data = new File("work/data/sessions");

			compiledtemplates.mkdirs();
			data.mkdirs();
		}

	}

	private static OptionParser setupOptions()
	{
		OptionParser parser = new OptionParser()
		{
			{
				accepts("createapp").withRequiredArg().ofType(String.class)
						.describedAs("Creates a new JaneMVC application");

				accepts("runapp")
						.withRequiredArg()
						.ofType(File.class)
						.describedAs(
								"A JAR file containing a JaneMVC application.");
			}
		};
		return parser;
	}

	public static void main(String[] args) throws Exception
	{

		MyLog.info("JaneMVC 0.1");

		OptionParser parser = setupOptions();

		OptionSet options = parser.parse(args);

		if (!options.hasOptions())
		{
			parser.printHelpOn(System.out);
			System.exit(0);
		} else
		{
			if (options.has("runapp"))
			{

				File appfile = (File) options.valueOf("runapp");

				if (appfile != null && appfile.exists())
				{
					MyLog.info(String.format("Loading application file %s...",
							appfile.getAbsolutePath()));

					SanityChecker sanitychecker = new SanityChecker(appfile);

					if (sanitychecker.check())
					{

						MyLog.info(String.format(
								"Application file %s is valid, running...",
								appfile.getAbsolutePath()));

						createWorkDir();

						AppDescriptor appdescriptor = sanitychecker
								.getAppDescriptor();

						Application application = new Application(appdescriptor);

						Server server = new Server(8181);
						server.setHandler(new JaneMVCHandler(application));

						server.start();
						server.join();

					} else
					{
						MyLog.severe(String
								.format("Application file %s is not a valid JaneMVC application. Exiting.",
										appfile.getAbsolutePath()));
					}

				} else
				{
					MyLog.severe("A .jar file containing an application must be provided (--runapp app.jar). Exiting.");
				}

			}

		}

	}

}
